﻿using NPOI.SS.Formula.Functions;
using OSSUtility.Communicate;
using OSSUtility.Device;
using ServiceStack;
using SharpDX.Direct2D1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ozone.Device
{

    /// <summary>
    /// Vince控制模块    配液补液 三工位Y轴步进电机 以及三工位补液使用
    /// </summary>
    public class DevVince : DevBase
    {
        public DevVince(int CommType, string FSrvIP, int FPort) : base(CommType, FSrvIP, FPort)
        {

        }



        // 发生 1 cfg\n  ASCII接收 查询所有状态
        //bdr=9600 cid=1 spd=19200.000000 acc=19200.000000 dec=19200.000000 mcs=6 cra=1.200000 crn=1.000000 crh=0.500000 pud=63 s3=0 s4=0 s5=0 s6=0 s1f=0 s2f=0 s3f=0 s4f=0 s5f=0 s6f=5 s1r=0 s2r=0 s3r=0 s4r=0 s5r=0 s6r=0 pae=0 dmd=0 dar=0 mdir=0 zmd=0 zar=0 osv=0 snr=0 zsd=-1600.000000 zsp=0 zcr=0.600000 msr=0 msv=0 psr=0 psv=0 sml=0 spl=0

        //设置加速电流
        //1 cfg cra=1.8

        //设置工作电流
        //1 cfg crn=1.8

        //保存参数指令

        //1 sav


        //1 cfg spd=38400  设置运行速度 38400
        /// <summary>
        /// 电机使能
        /// </summary>
        /// <returns></returns>
        public bool ENA()
        {
            bool temperature = false;

            try
            {
                string command = "1 ena\n";
                byte[] byteRcv = session_.sendAndReadByte(command);
                //收到FF 01 02 00 00 00 00 00 0F 7F 7F 31 70 00 00 0C 66 1F 00 38 FE
                if (byteRcv != null && byteRcv.Length == 21)
                {
                    temperature = true;
                }
            }
            catch (Exception)
            {
                temperature = false;
            }
            return temperature;
        }

        /// <summary>
        /// 触碰光开回原点
        /// </summary>
        /// <returns></returns>
        public bool GoOrigin()
        {
            //整个Z轴的行程是25000 正常走30000一定可以触碰到光开
            bool temperature = Pos(300000);
            //往前走一点远离光开
            temperature = Pos(-10000);
            return temperature;
        }

        /// <summary>
        /// 绝对位置运行
        /// -2,147,483,647~2,147,483,648，参数类型为整型
        /// </summary>
        /// <returns></returns>
        public bool Pos(int poslocation)
        {
            bool temperature = false;
            try
            {
                string command = "1 pos " + poslocation + " \n";
                byte[] byteRcv = session_.sendAndReadByte(command);
                if (byteRcv != null && byteRcv.Length == 21)
                {
                    temperature = true;
                    int Number = 0;

                    while (true)
                    {
                        Thread.Sleep(1000);
                        if (StsGetNowLocation() == poslocation)
                        {
                            temperature = true;
                            break;
                        }
                        if (Number > 10)
                        {
                            temperature = false;
                            break;
                        }
                        Number++;
                    }



                }
            }
            catch (Exception)
            {

                temperature = false;
            }

            return temperature;

        }






        /// <summary>
        /// 状态查询获取当前位置
        /// </summary>
        /// <returns></returns>
        public int StsGetNowLocation()
        {
            int temperature = 0;
            ValueInfo valueInfo = new ValueInfo();
            try
            {
                string command = "1 sts\n";
                byte[] byteRcv = session_.sendAndReadByte(command);
                if (byteRcv != null && byteRcv.Length == 21)
                {
                    byte[] result = byteRcv.Skip(8).Take(5).ToArray();

                    Convert(result, ref valueInfo);
                    if (valueInfo != null)
                    {
                        temperature = valueInfo.IntValue;
                    }
                }
            }
            catch (Exception)
            {

                temperature = 0;
            }

            return temperature;

        }



        public class ValueInfo
        {
            public float FloatValue { get; set; }
            public int IntValue { get; set; }
            public uint UIntValue { get; set; }
        }

        public static void Convert(byte[] data, ref ValueInfo info)
        {
            if (data.Length < 5)
                throw new ArgumentException("需要至少5字节数据");

            // 1. 解析无符号整数（原逻辑）
            info.UIntValue = data[0];

            for (int i = 1; i < 5; i++)
            {

                info.UIntValue = (info.UIntValue << 7) | data[i];
            }

            // 2. 自动填充有符号整数（直接类型转换）
            info.IntValue = (int)info.UIntValue;

            // 3. 解析浮点数（假设字节序为小端）
            if (data.Length >= 4)
            {
                byte[] floatBytes = new byte[4];
                Array.Copy(data, 0, floatBytes, 0, 4);
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(floatBytes); // 转为大端序处理
                }
                info.FloatValue = BitConverter.ToSingle(floatBytes, 0);
            }
        }










        /// <summary>
        /// 补液开始  速度 19200
        /// </summary>
        /// <param name="poslocation"></param>
        /// <returns></returns>
        public bool mov(int poslocation)
        {
            //1 mov spd = 19200
            bool temperature = false;
            try
            {
                string command = "1 mov " + poslocation + "\r\n";
                byte[] byteRcv = session_.sendAndReadByte(command);
                //收到FF 01 02 04 38 58 00 00 00 04 3F 17 40 00 00 0C 40 2F 00 68 FE 

                //FF 01 02 00 00 00 00 00 00 0A 61 42 1E 00 00 0C 42 0F 00 75 FE
                //FF 01 02 04 38 58 00 00 00 0B 17 10 73 00 00 0C 40 2F 00 7B FE
                if (byteRcv != null && byteRcv.Length == 21)
                {
                    temperature = true;
                }
            }
            catch (Exception)
            {

                temperature = false;
            }

            return temperature;

        }




        /// <summary>
        /// 补液停止
        /// </summary>
        /// <returns></returns>
        public bool stp()
        {
            bool temperature = false;
            try
            {
                string command = "1 stp \r\n";
                byte[] byteRcv = session_.sendAndReadByte(command);
                //收到FF 01 02 04 38 58 00 00 00 0A 61 42 1D 00 00 0C 40 2F 00 30 FE
                if (byteRcv != null && byteRcv.Length == 21)
                {
                    temperature = true;
                }
            }
            catch (Exception)
            {

                temperature = false;
            }

            return temperature;

        }




        /// <summary>
        /// 安装瓶盖
        /// </summary>
        /// <returns></returns>
        public bool Installbottlecap()
        {

            bool temperature = false;


            try
            {
                //站点
                byte stationid = 0x01;
                //功能码
                byte funcode = 0x06;
                //起始地址
                ushort startAddr = 0x01;
                //发送数据
                byte[] bytesData = new byte[2];
                bytesData[1] = 0x00;
                bytesData[0] = 0x01;
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, bytesData);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {

                throw;
            }

            return temperature;

        }

        /// <summary>
        /// 卸瓶盖
        /// </summary>
        /// <returns></returns>
        public bool UnInstallbottlecap()
        {

            bool temperature = false;


            try
            {
                //站点
                byte stationid = 0x01;
                //功能码
                byte funcode = 0x06;
                //起始地址
                ushort startAddr = 0x01;
                //发送数据
                byte[] bytesData = new byte[2];
                bytesData[1] = 0x00;
                bytesData[0] = 0x01;
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, bytesData);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {

                throw;
            }

            return temperature;

        }





        /// <summary>
        /// 补液
        /// </summary>
        /// <returns></returns>
        public bool FluidInfusion()
        {

            bool temperature = false;


            try
            {
                //站点
                byte stationid = 0x01;
                //功能码
                byte funcode = 0x06;
                //起始地址
                ushort startAddr = 0x01;
                //发送数据
                byte[] bytesData = new byte[2];
                bytesData[1] = 0x00;
                bytesData[0] = 0x01;
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, bytesData);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {

                throw;
            }

            return temperature;

        }


        /// <summary>
        /// 获取三工位运行状态  
        /// true  运行中 
        /// false  停止状态
        /// </summary>
        /// <returns></returns>
        public bool GetThreeStationRunState()
        {

            bool temperature = false;


            try
            {
                //站点
                byte stationid = 0x01;
                //功能码
                byte funcode = 0x06;
                //起始地址
                ushort startAddr = 0x01;
                //发送数据
                byte[] bytesData = new byte[2];
                bytesData[1] = 0x00;
                bytesData[0] = 0x01;
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, bytesData);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {

                throw;
            }

            return temperature;

        }


        /// <summary>
        /// 馏分清洗
        /// </summary>
        /// <returns></returns>
        public bool CollectCleaning()
        {

            bool temperature = false;


            try
            {
                //站点
                byte stationid = 0x01;
                //功能码
                byte funcode = 0x06;
                //起始地址
                ushort startAddr = 0x01;
                //发送数据
                byte[] bytesData = new byte[2];
                bytesData[1] = 0x00;
                bytesData[0] = 0x01;
                List<byte> returnbytes = Modbus.writeFreameRTUSingle(stationid, funcode, startAddr, bytesData);
                byte[] byteRcv = session_.sendAndReadByteLock(returnbytes.ToArray());
                if (byteRcv != null)
                {
                    temperature = true;
                }
            }
            catch (Exception ex)
            {

                throw;
            }

            return temperature;

        }








    }
}
